package me.jessyan.mvparms.demo.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.platform.ai.control.R;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.mvparms.demo.di.component.DaggerUserComponent;
import me.jessyan.mvparms.demo.di.module.UserModule;
import me.jessyan.mvparms.demo.mvp.contract.UserContract;
import me.jessyan.mvparms.demo.mvp.model.entity.BluRxBean;
import me.jessyan.mvparms.demo.mvp.model.entity.User;
import me.jessyan.mvparms.demo.mvp.model.logic.AllDialogUtil;
import me.jessyan.mvparms.demo.mvp.presenter.UserPresenter;

import me.jessyan.mvparms.demo.mvp.ui.adapter.ScanBlueToothAdapter;
import me.jessyan.mvparms.demo.mvp.ui.receiver.BltService;
import me.jessyan.mvparms.demo.mvp.ui.receiver.BlueToothReceiver;
import me.jessyan.mvparms.demo.mvp.ui.view.WrapHeightLinearLayoutManager;
import me.jessyan.mvparms.demo.mvp.widget.BltContant;
import me.jessyan.mvparms.demo.mvp.widget.BltManager;
import me.jessyan.mvparms.demo.util.ThreadPoolProxyFactory;

// 注册界面
public class BlueToothActivity extends BaseActivity<UserPresenter> implements UserContract.View, OnRefreshListener {
    private BluetoothAdapter bluetoothadapter;
    private ScanBlueToothAdapter adapter;
    private List<BluetoothDevice> listdevice;
    private BlueToothReceiver blueToothReceiver = new BlueToothReceiver();
    private int connectsuccess = 12;//连接成功
    private Context mContext;

    @BindView(R.id.rv)
    RecyclerView listview;

    @BindView(R.id.tv_title)
    TextView mTitle;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerUserComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .userModule(new UserModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_bule_tooth; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mContext = this;
        init();
        if(!BluetoothAdapter.getDefaultAdapter().isEnabled()){
            BluetoothAdapter.getDefaultAdapter().enable();
        }
        BltManager.getInstance().initBltManager(this);
        startscan();
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        //checkNotNull(message);
        //ArmsUtils.snackbarText(message);
        if (!message.isEmpty()) {

        }
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void setAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void loginReturn(User user) {

    }

    @Override
    public void logout() {

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        startscan();
    }

    @Override
    public void uploadResult(String string) {

    }

    @OnClick(R.id.iv_back)
    public void onBack(View v){
        super.onBackPressed();
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver(blueToothReceiver, blueToothReceiver.makeFilter());
        EventBus.getDefault().register(this);
    }

    @Override
    public void killMyself() {
        unregisterReceiver(blueToothReceiver);
//        BltService.getInstance().cancel();
        BltManager.getInstance().stopSearthBltDevice();
        EventBus.getDefault().unregister(this);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        killMyself();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        killMyself();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                startscan();
            }
        }
    }

    /**
     * 组件初始化
     */
    private void init() {
        mTitle.setText("蓝牙连接");
        mRefreshLayout.setOnRefreshListener(this);
        listdevice = new ArrayList<>();
        /**
         * listview监听事件 即配对
         */
        ArmsUtils.configRecyclerView(listview,new WrapHeightLinearLayoutManager(this));
        adapter = new ScanBlueToothAdapter(listdevice, new ScanBlueToothAdapter.ConfigBlueToothListener() {

            @Override
            public void configBlueTooth(BluetoothDevice bean,int position) {
                AllDialogUtil.getInstance().initWaitDialog(mContext);
                BltManager.getInstance().createBond(bean, new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        AllDialogUtil.getInstance().dismissWaitDialog();
                        if(msg.what == 4){

                        }
                    }
                });
            }
        });
        listview.setAdapter(adapter);
    }

    /**
     * 开始扫描蓝牙
     */
    private void startscan() {
        Log.i("lzd","进行设备扫描");
        listdevice.clear();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        /**
         * 开启蓝牙服务端
         */
        BltManager.getInstance().clickBlt(this,BltContant.BLUE_TOOTH_SEARTH);
    }

    /**
     * EventBus 异步
     * 1:找到设备
     * 2：扫描完成
     * 3：开始扫描
     * 4.配对成功
     * 11:有设备连接进来
     * 12:连接成功
     */
    @Subscriber
    public void onMessageEvent(BluRxBean bluRxBean) {
        Intent intent = null;
        switch (bluRxBean.getId()) {
            case 1:
                String s = bluRxBean.getBluetoothDevice().getName();
                if (!listdevice.contains(s))
                    listdevice.add(bluRxBean.getBluetoothDevice());
                adapter.notifyDataSetChanged();
                break;
            case 2:
                break;
            case 3:
                Toast.makeText(this, "开始扫描蓝牙，请稍后...", Toast.LENGTH_SHORT).show();
                break;
            case 4://配对成功
                Set<BluetoothDevice> bondedDevices = bluetoothadapter.getBondedDevices();
                for (BluetoothDevice bondedDevice : bondedDevices) {
                    bondedDevice.getAddress();
                }
                listdevice.clear();
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
                if (bluetoothadapter.isDiscovering()) {
                    bluetoothadapter.cancelDiscovery();
                }
                bluetoothadapter.startDiscovery();
                break;
            case 10:
                Toast.makeText(mContext, "配对失败", Toast.LENGTH_SHORT).show();
                break;
            case 11:
                int p = listdevice.indexOf(bluRxBean.getBluetoothDevice());
                Log.i("lzd","配对中的设备："+p+","+bluRxBean.getBluetoothDevice().getName()+bluRxBean.getBluetoothDevice().getBondState());
                listdevice.set(p,bluRxBean.getBluetoothDevice());
                adapter.notifyDataSetChanged();
                Toast.makeText(this,"蓝牙配对中",Toast.LENGTH_SHORT).show();
                break;
            case 12:
                int i = listdevice.indexOf(bluRxBean.getBluetoothDevice());
                Log.i("lzd","配对中的设备："+i+","+bluRxBean.getBluetoothDevice().getName()+bluRxBean.getBluetoothDevice().getBondState());
                listdevice.set(i,bluRxBean.getBluetoothDevice());
                adapter.notifyDataSetChanged();
                Toast.makeText(this,"蓝牙已配对",Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }






}
